{% extends 'index.html' %} 
{% block ace-content %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<style type="text/css">
	#compile-editor {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }	
</style>
{% endblock %}
{%block page-content %}
{% if order.order_status == 4 and order.prem == 1 or order.order_status == 8 and order.prem == 1  %}
	<div id="page-wrapper">
	
		<div class="row">
			<div class="col-lg-12">
				<h1 class="page-header">
					<i class="fa fa-tasks"></i>&nbsp;
					<code>执行SQL</code>
				</h1>
			</div>
			<!-- /.col-lg-12 -->
		</div>
	
	
		<div class="row">
				<div class="col-lg-12">
					<div class="panel panel-default">
						<div class="panel-heading"><i class="fa fa-history"></i> 执行需要上线的SQL</div>
						<div class="panel-body">
						<div class="row">
							<div class="col-lg-6">
								<legend>
									<i class="fa  fa-paper-plane"></i> SQL信息
								</legend>
								<form role="form" method="post" id="audit_sql_order">
									{% csrf_token %}
									<div class="form-group">
	 									<label>用途<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>
										<textarea class="form-control" rows="3" id="order_desc" disabled>{{order.order_subject}}</textarea>								
									</div>	
									<div class="form-group">
										<label>上线SQL<i class="fa fa-info-circle" data-toggle="tooltip" title="即将被执行上线的SQL"></i></label>
										<div id="compile-editor" class="ace_editor">{{order.sql_audit_order.order_sql}}</div>
										<p class="help-block">例如：insert into tablename (xxx,xxx,xxx) values (xxx,xxx,xxx);</p>										
									</div>
									{% if order.order_status == 1 %}						
										<button type="button" class="btn btn-default disabled">未授权</button>
									{% else %}
										<button type="button" class="btn btn-default" onclick="auditSqlOrder(this,'exec')">执行</button>
									{% endif %}
							</div>
							<!-- /.col-lg-6 (nested) -->
							<div class="hr hr32 hr-dotted"></div>
							<div class="col-lg-6">
								<legend>
									<i class="fa  fa-paper-plane-o"></i> 数据库选择
								</legend>
								<div class="form-group">
									<label>环境类型</label> <br> 
									<input type="text" class="form-control" id="db_env" name="db_env" value="{% if order.sql_audit_order.order_db.db_env == 'test' %}测试环境{%else%}生产环境{%endif%}" disabled> </input>						
								</div>								
								<div class="form-group">
									<label>所属项目</label> <br> 
									<input type="text" class="form-control" id="db_project" name="db_project" value="{{order.sql_audit_order.order_db.db_service.project.project_name}}" disabled> </input>						
								</div>								
								<div class="form-group">
									<label>业务类型</label> <br> 
									<input type="text" class="form-control" id="db_service" name="db_service" value="{{order.sql_audit_order.order_db.db_service.service_name}}" disabled> </input>						
								</div>									
								<div class="form-group">
									<label>数据库</label> <br> 
									<input type="text" class="form-control" id="order_db" name="order_db" value="{{order.sql_audit_order.order_db.db_name}}({{order.sql_audit_order.order_db.db_host}})-{{order.sql_audit_order.order_db.db_mark|default:""}}" disabled> </input>								
								</div>									
<!-- 								<div class="form-group">
									<label>数据库</label> <br> 
									<input type="text" class="form-control" id="order_db" name="order_db" value="{{order.sql_audit_order.order_db.db_host}} - {{order.sql_audit_order.order_db.db_name}}" disabled> </input>								
								</div>	 -->					
								<div class="form-group">
									
									<label>执行人<i class="fa fa-info-circle"
										data-toggle="tooltip" title="工单发送给谁执行"></i></label> 
										<input type="text" class="form-control" id="order_executor" name="order_executor" value="{{order.order_executor}}" disabled> </input>								
									<p class="help-block">例如：admin</p>
								</div>
							</div>
							<div class="col-lg-6" id="auditResultDiv" style="display:none;">
								<legend>
									<i class="fa  fa-spinner  "></i> SQL执行结果
								</legend>
								<div>
	                                <table class="table table-hover" id='auditResult'>
					                    <thead>
					                        <tr>
					                            <th>#</th>
					                            <th>SQL</th>
					                            <th>影响行</th>
					                            <th>错误原因</th>
					                        </tr>
					                	</thead>                             
	                                </table>								
								</div>
							</div>						
							<!-- /.col-lg-6 (nested) -->
							<div class="hr hr32 hr-dotted"></div>
							</form>
						</div>
	
						</div>
						<div class="panel-footer"></div>
					</div>
				</div>
	
		</div>
		
	
	
	</div>
	
	
	
	<script type="text/javascript">
	
		function setAceEditMode(model) {
			var editor = ace.edit("compile-editor");
			require("ace/ext/old_ie");
			var langTools = ace.require("ace/ext/language_tools");
			editor.setTheme("ace/theme/monokai");
			editor.getSession().setMode("ace/mode/" + model);
			editor.setReadOnly(true); 
			editor.setShowPrintMargin(false);
			editor.setOptions({
			    enableBasicAutocompletion: true,
			    enableSnippets: true,
			    enableLiveAutocompletion: true
			}); 
					 
		};
		setAceEditMode("mysql");
	
		$(document).ready(function() {
		    $('#taskTableList').DataTable();
		} );  
	    $(function () { 
	    	$("[data-toggle='popover']").popover();
	    });	
	    {% if order.order_status == 8 %}
			function auditSqlOrder(obj,op) {	
				var btnObj = $(obj);
				var required = ["order_db","order_executor"];
				btnObj.attr('disabled',true);
					var server_data = {};
					var form = document.getElementById('audit_sql_order');
					for (var i = 0; i < form.length; ++i) {
						var name = form[i].name;
						var value = form[i].value;	
						idx = $.inArray(name, required);						
						if (idx >= 0 && value.length == 0){
							window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
							btnObj.removeAttr('disabled');
							return false;					};					
					};				
					var editor = ace.edit("compile-editor");
				    var order_sql = editor.getSession().getValue();  
					$.ajax({
						dataType: "JSON",
						url:'/db/sql/order/run/{{order.id}}/', //请求地址
						type:"POST",  //提交类似
						data:{
							'type':'exec',
						},  //提交参数
						success:function(response){
							btnObj.removeAttr('disabled');
							if (response["code"] == 200){
								window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
							}
							else {
								window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
							}
							{% if order.sql_audit_order.order_type == 'online' %}
							document.getElementById("auditResultDiv").style.display = ""; 
													
							var resultHTML =  '<table class="table table-hover" id="auditResult">' +
		                    '<thead>' +
		                        '<tr>' +
		                            '<th>#</th>' +
		                            '<th>SQL</th>' +
		                            '<th>影响行</th>' +
		                            '<th>错误原因</th>' +
		                        '</tr>' +
		                	'</thead>' +
		                	'<tbody>'
						     var trHtml = ''
						     for (var i=0;i< response['data'].length;i++){
						    	 trHtml +=   '<tr>' + 
						                         '<td>'+ i +'</td>' + 
						                         '<td>'+ response['data'][i]['sql'] +'</td>' + 
						                         '<td>'+ response['data'][i]['row'] +'</td>' + 
						                         '<td>'+ response['data'][i]['errmsg'] +'</td>' + 
						                     '</tr>'
						     }
							resultHTML = resultHTML + trHtml + '</tbody></table>'
							$('#auditResult').html(resultHTML);	
							{% endif %}
						},
				    	error:function(response){
				    		btnObj.removeAttr('disabled');
				    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				    	}
					});	
				}
		{% endif %}
	
		
	
	
		
	</script>
<!-- 	回滚页面 -->
{% elif order.order_status == 5 and order.prem == 1 and order.sql_audit_order.order_type == 'online' or order.order_status == 6 and order.prem == 1 and order.sql_audit_order.order_type == 'online' or order.order_status == 9 and order.prem == 1 and order.sql_audit_order.order_type == 'online' %}
	<div id="page-wrapper">
	
		<div class="row">
			<div class="col-lg-12">
				<h1 class="page-header">
					<i class="fa fa-tasks"></i>&nbsp;
					<code>SQL回滚</code>
				</h1>
			</div>
			<!-- /.col-lg-12 -->
		</div>
	
	
		<div class="row">
				<div class="col-lg-12">
					<div class="panel panel-default">
						<div class="panel-heading"><i class="fa fa-history"></i> 回滚已上线的SQL</div>
						<div class="panel-body">
						<div class="row">
							<div class="col-lg-6">
								<legend>
									<i class="fa  fa-paper-plane"></i> SQL信息
								</legend>
								<form role="form" method="post" id="audit_sql_order">
									{% csrf_token %}
								<div class="form-group">
									<label>环境类型</label> <br> 
									{% if order.sql_audit_order.order_db.db_env == 'test' %}
									<input type="text" class="form-control" id="order_env" name="db_env" value="测试" disabled> </input>	
									{% else %}	   
									<input type="text" class="form-control" id="order_env" name="db_env" value="正式" disabled> </input>	
									{% endif %}							
								</div>		
								<div class="form-group">
									<label>所属项目</label> <br> 
									<input type="text" class="form-control" id="db_project" name="db_project" value="{{order.sql_audit_order.order_db.db_service.project.project_name}}" disabled> </input>						
								</div>																	
								<div class="form-group">
									<label>业务类型</label> <br> 
									<input type="text" class="form-control" id="db_service" name="db_service" value="{{order.sql_audit_order.order_db.db_service.service_name}}" disabled> </input>						
								</div>									
								<div class="form-group">
									<label>数据库</label> <br> 
									<input type="text" class="form-control" id="order_db" name="order_db" value="{{order.sql_audit_order.order_db.db_name}}({{order.sql_audit_order.order_db.db_host}})" disabled> </input>								
								</div>						
								<div class="form-group">
									<label>执行人<i class="fa fa-info-circle"
										data-toggle="tooltip" title="工单发送给谁执行"></i></label> 
										<input type="text" class="form-control" id="order_executor" name="order_executor" value="{{order.order_executor}}" disabled> </input>								
									<p class="help-block">例如：admin</p>
								</div>									
								<div class="form-group">
	 									<label>用途<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>
										<textarea class="form-control" rows="3" id="order_desc" disabled>{{order.order_subject}}</textarea>																						
								</div>	
								<div class="form-group">
									<label>已上线SQL<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>		
									<div id="compile-editor" class="ace_editor">{{order.sql_audit_order.order_sql}}</div>
									<p class="help-block">例如：insert into tablename (xxx,xxx,xxx) values (xxx,xxx,xxx);</p>									
								</div>
									{% if order.order_status == 5 and rbkSql != 0 %}						
										<button type="button" class="btn btn-default" onclick="rbkSqlOrder(this)" id="auditContol">回滚</button>
									{% elif rbkSql == 0 or order.order_status == 7 %}
										<button type="button" class="btn btn-default disabled" >不能回滚</button>
									{% else %}
										<button type="button" class="btn btn-default disabled" >已回滚</button>
									{% endif %}
							</div>
							<!-- /.col-lg-6 (nested) -->
							<div class="hr hr32 hr-dotted"></div>
							<div class="col-lg-6">
								<legend>
									<i class="fa  fa-exclamation"></i> 原SQL执行结果
								</legend>	
	                            <div class="table-responsive">
	                                <table class="table table-hover">
	                                    <thead>
	                                        <tr>
	                                            <th>#</th>
	                                            <th>SQL</th>
	                                            <th>影响行</th>
	                                            <th>状态</th>
	                                            <th>执行结果</th>
	                                            {% if order.order_status == 7 %}
	                                            	<th>失败原因</th>
	                                            {% endif %}
	                                        </tr>
	                                    </thead>
	                                    <tbody>
	                                    	{% for ds in sqlResultList %}
	                                        <tr>
	                                        	<td>{{ds.id}}</td>
	                                            <td>
	                                            	<a href="#" class="tooltip-test" data-toggle="tooltip" title="{{ds.sqltext}}">{{ds.sqltext|slice:":20" }}...</a>
	                                            </td>
	                                            <td>{{ds.affectrow}}</td>
	                                            <td>{{ds.stage}}</td>
	                                            <td>{{ds.stagestatus}}</td>
	                                            {% if order.order_status == 7 %}
	                                            	<td>{{ds.errormessage}}</td>
	                                            {% endif %}	                                            
	                                        </tr>
	                                        {% endfor %}
	                                    </tbody>
	                                </table>
	                            </div>	
	                            <legend></legend>
	                            {% if oscStatus %}
								<legend>
									<i  class="fa  fa-spinner"></i> 执行进度:<code id="osc_percent">{{oscStatus.data.percent}}%</code>&nbsp;&nbsp;&nbsp;&nbsp;剩余时间：<code id="osc_time">{{oscStatus.data.timeRemained}}</code>&nbsp;&nbsp;&nbsp;&nbsp;
									<div class="btn-group btn-group-xs pull-right">
										<button type="button" class="btn btn-success btn-xs" id="stop_osc" onclick="stopOscSql(this)" {% if oscStatus.data.percent >= 100 %} disabled {%endif%}>终止</button>
									</div>
									<div class="form-group" id="osc_per">							
										<div class="form-group progress progress-striped active">
											<div class="progress-bar progress-bar-success" role="progressbar"
												 aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"
												 style="width: {{oscStatus.data.percent}}%;">
												<span class="sr-only">40% 完成</span>
											</div>
										</div>		
									</div>						
								</legend>	
								{% endif %}                            													
								<legend>
									<i class="fa  fa-github-alt"></i> 以下为回滚SQL语句
								</legend>	
								<pre>{% for ds in rollBackSql %}<p>{{ ds }}</p>{% endfor %}</pre>
													
							</div>											
							<!-- /.col-lg-6 (nested) -->
							<div class="hr hr32 hr-dotted"></div>
							</form>
						</div>
	
						</div>
						<div class="panel-footer"></div>
					</div>
				</div>
	
		</div>
		
	
	
	</div>
	
	
	
	<script type="text/javascript">
		
 		function setAceEditMode(model) {
			var editor = ace.edit("compile-editor");
			require("ace/ext/old_ie");
			var langTools = ace.require("ace/ext/language_tools");
			editor.setTheme("ace/theme/monokai");
			editor.getSession().setMode("ace/mode/" + model);
			editor.setReadOnly(true); 
			editor.setShowPrintMargin(false);
			editor.setOptions({
			    enableBasicAutocompletion: true,
			    enableSnippets: true,
			    enableLiveAutocompletion: true
			}); 
					 
		};
		setAceEditMode("mysql"); 
	
		$(document).ready(function() {
		    $('#taskTableList').DataTable();
		} );  
	    $(function () { 
	    	$("[data-toggle='popover']").popover();
	    });	
	    {% if order.order_status == 5 %}
			function rbkSqlOrder(obj) {	
				var btnObj = $(obj);
				btnObj.attr('disabled',true);				 
					$.ajax({
						dataType: "JSON",
						url:'/db/sql/order/run/{{order.id}}/', //请求地址
						type:"POST",  //提交类似
						data:{
							'type':'rollback',
						},  //提交参数
						success:function(response){
							btnObj.removeAttr('disabled');
							if (response["code"] == 200){
								window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
								location.reload();
							}
							else {
								window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
							};				
						},
				    	error:function(response){
				    		btnObj.removeAttr('disabled');
				    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				    	}
					});	
				}
		{% endif %}
		
		{% if oscStatus and oscStatus.data.percent < 100  %}

			var interval = setInterval(function(){  
			        $.ajax({  
			            url : '/db/sql/order/osc/{{order.sql_audit_order.id}}/',  
			            type : 'post',
						data:{
							'model':'query'
						},
			            success : function(result){
			            	if( result["data"]["percent"] > 100 ){
								var perHtml = '<div class="form-group" id="osc_per">' + 						
													'<div class="form-group progress progress-striped active">' +
														'<div class="progress-bar progress-bar-success" role="progressbar"' +
															 'aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"' +
															 'style="width:100%;">' +
														'</div>' +
													'</div>' +		
												'</div>'	
								var timeHtml = '<code id="osc_time">00:00</code>';
								var osc_percent = '<code id="osc_percent">100%</code>';
								document.getElementById("osc_per").innerHTML= perHtml;
								document.getElementById("osc_time").innerHTML= timeHtml;
								document.getElementById("osc_percent").innerHTML= osc_percent;	
								$("#stop_osc").attr("disabled", true);
								clearInterval(interval);
			            	}
			            	else{
								var perHtml = '<div class="form-group" id="osc_per">' + 						
												'<div class="form-group progress progress-striped active">' +
													'<div class="progress-bar progress-bar-success" role="progressbar"' +
														 'aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"' +
														 'style="width:' + result["data"]["percent"] + '%;">' +
													'</div>' +
												'</div>' +		
											'</div>'	
								var timeHtml = '<code id="osc_time">' + result["data"]["timeRemained"] +'</code>'
								var osc_percent = '<code id="osc_percent">'+ result["data"]["percent"] +'%</code>'
								document.getElementById("osc_per").innerHTML= perHtml;
								document.getElementById("osc_time").innerHTML= timeHtml;
								document.getElementById("osc_percent").innerHTML= osc_percent;		            		
			            	}
			            },
				    	error:function(response){
				    		clearInterval(interval);
				    	}	            
			        });  
			    },3000); 
			
			function stopOscSql(obj) {
				var btnObj = $(obj);
				btnObj.attr('disabled',true);	
				$.ajax({
		            url : '/db/sql/order/osc/{{order.sql_audit_order.id}}/',  
		            type : 'post',
					data:{
						'model':'stop'
					},
					success:function(response){
						if (response['code'] == 200){
							window.wxc.xcConfirm(response['data'], window.wxc.xcConfirm.typeEnum.success);
						}
						else{
							window.wxc.xcConfirm(response['data'],  window.wxc.xcConfirm.typeEnum.error);
						};
						clearInterval(interval);
					},
			    	error:function(response){
			    		btnObj.removeAttr('disabled');
			    		window.wxc.xcConfirm("网络错误，终止osc进程失败。", window.wxc.xcConfirm.typeEnum.error);
		/* 	    		location.reload(); */
			    	}
				})	
			} 		
		 
		{% endif %}

	</script>


	
{% else %}	

	<div id="page-wrapper">
	
		<div class="row">
			<div class="col-lg-12">
				<h1 class="page-header">
					<i class="fa fa-tasks"></i>&nbsp;
					<code>SQL工单详情</code>
				</h1>
			</div>
			<!-- /.col-lg-12 -->
		</div>
	
	
		<div class="row">
				<div class="col-lg-12">
					<div class="panel panel-default">
						<div class="panel-heading"></div>
						<div class="panel-body">
						<div class="row">
							<div class="col-lg-8">
								<legend>
									<i class="fa  fa-paper-plane"></i> SQL信息
								</legend>
								<form role="form" method="post" id="audit_sql_order">
									{% csrf_token %}
								<div class="form-group">
									<label>环境类型</label> <br> 
									{% if order.sql_audit_order.order_db.db_env == 'test' %}
									<input type="text" class="form-control" id="order_env" name="db_env" value="测试" disabled> </input>	
									{% else %}	   
									<input type="text" class="form-control" id="order_env" name="db_env" value="正式" disabled> </input>	
									{% endif %}							
								</div>										
								<div class="form-group">
									<label>所属项目</label> <br> 
									<input type="text" class="form-control" id="db_project" name="db_project" value="{{order.sql_audit_order.order_db.db_service.project.project_name}}" disabled> </input>						
								</div>										
								<div class="form-group">
									<label>业务类型</label> <br> 
									<input type="text" class="form-control" id="db_service" name="db_service" value="{{order.sql_audit_order.order_db.db_service.service_name}}" disabled> </input>						
								</div>									
								<div class="form-group">
									<label>数据库</label> <br> 
									<input type="text" class="form-control" id="order_db" name="order_db" value="{{order.sql_audit_order.order_db.db_name}}({{order.sql_audit_order.order_db.db_host}})" disabled> </input>								
								</div>										
<!-- 								<div class="form-group">
									<label>数据库</label> <br> 
									<input type="text" class="form-control" id="order_db" name="order_db" value="{{order.sql_audit_order.order_db.db_host}} - {{order.sql_audit_order.order_db.db_name}}" disabled> </input>								
								</div> -->		
												
								<div class="form-group">
									<label>执行人<i class="fa fa-info-circle"
										data-toggle="tooltip" title="工单发送给谁执行"></i></label> 
										<input type="text" class="form-control" id="order_executor" name="order_executor" value="{{order.order_executor}}" disabled> </input>								
									<p class="help-block">例如：admin</p>
								</div>	
								<div class="form-group">
									<label>取消原因</label> <br> 
									<input type="text" class="form-control" id="order_cancel" name="order_db" value="{{order.order_cancel|default:""}}" disabled> </input>								
								</div>																
									<div class="form-group">
	 									<label>用途<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>
										<textarea class="form-control" rows="3" id="order_desc" disabled>{{order.order_subject}}</textarea>	

									</div>	
								<div class="form-group">
										<label>SQL内容<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>														
										<div id="compile-editor" class="ace_editor">{{order.sql_audit_order.order_sql}}</div>
										<p class="help-block">例如：insert into tablename (xxx,xxx,xxx) values (xxx,xxx,xxx);</p>							
								</div>									
							</div>
							<div class="hr hr32 hr-dotted"></div>
							</form>
						</div>
	
						</div>
						<div class="panel-footer"></div>
					</div>
				</div>
	
		</div>
		
	
	
	</div>	
	<script type="text/javascript">
		function setAceEditMode(model) {
			var editor = ace.edit("compile-editor");
			require("ace/ext/old_ie");
			var langTools = ace.require("ace/ext/language_tools");
			editor.setTheme("ace/theme/monokai");
			editor.getSession().setMode("ace/mode/" + model);
			editor.setReadOnly(true); 
			editor.setShowPrintMargin(false);
			editor.setOptions({
			    enableBasicAutocompletion: true,
			    enableSnippets: true,
			    enableLiveAutocompletion: true
			}); 
					 
		};
		setAceEditMode("mysql");
	</script>
{% endif %}

{% if errinfo %}
	<script type="text/javascript">
		window.wxc.xcConfirm("{{errinfo}}", window.wxc.xcConfirm.typeEnum.error);
	</script>
{% endif %}

{% endblock %}
